import os, sys, gc
try:
    import PyPDF2, wordninja
except:
    os.system("python -m pip install PyPDF2 wordninja")
    import PyPDF2, wordninja
gc.disable()

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")

def main(a):
    pdf= open(a, 'rb')
    pdfReader=PyPDF2.PdfFileReader(pdf, strict=False)
    if os.getcwd()==os.path.dirname(os.path.abspath(__file__)):
        os.chdir(os.path.dirname(a))

    with open(os.path.basename(a).rsplit(".", 1)[0]+".txt", "w", encoding="utf8") as f:
        for i in range(pdfReader.numPages):
            p= "\t%s / %s" %(i, pdfReader.numPages)
            print(p, end="\r")
            page= pdfReader.getPage(i)
            v= page.extractText().replace('\n', '').lower()
            v2= ' '.join(wordninja.split(v))
            f.write(v2)
            f.write('\n')
    pdf.close()

if __name__ == "__main__":
    args = sys.argv
    if not len(args) <2:
        if args[1][-4:] == '.pdf':
            main(args[1])
    else:
        print("\tTo transform a pdf to text,")
        print("\tUse the tool via:")
        print("\tpython [*this] [*path*]")
        